"""
执行引擎

提供多种交易执行算法，包括TWAP、VWAP、冰山单等高级执行策略。
"""

from abc import ABC, abstractmethod
from enum import Enum
from typing import Dict, List, Optional, Any, Callable, AsyncGenerator
from datetime import datetime, timedelta
from dataclasses import dataclass, field
import asyncio
import math
from decimal import Decimal
import pandas as pd

from .order_manager import Order, OrderManager, OrderType, OrderStatus, OrderSide


class ExecutionAlgorithm(Enum):
    """执行算法枚举"""
    MARKET = "market"  # 市价执行
    LIMIT = "limit"  # 限价执行
    TWAP = "twap"  # 时间加权平均价格
    VWAP = "vwap"  # 成交量加权平均价格
    POV = "pov"  # 参与率算法
    ICEBERG = "iceberg"  # 冰山算法
    SNIPER = "sniper"  # 狙击算法
    GUERRILLA = "guerrilla"  # 游击算法


class ExecutionStatus(Enum):
    """执行状态枚举"""
    PENDING = "pending"  # 待执行
    RUNNING = "running"  # 执行中
    PAUSED = "paused"  # 暂停
    COMPLETED = "completed"  # 完成
    CANCELLED = "cancelled"  # 取消
    ERROR = "error"  # 错误


@dataclass
class ExecutionParams:
    """执行参数"""
    algorithm: ExecutionAlgorithm  # 执行算法
    total_quantity: Decimal  # 总数量
    time_horizon: timedelta  # 执行时间窗口
    participation_rate: float = 0.1  # 参与率 (0-1)
    price_limit: Optional[Decimal] = None  # 价格限制
    slice_size: Optional[Decimal] = None  # 切片大小
    min_slice_size: Optional[Decimal] = None  # 最小切片大小
    max_slice_size: Optional[Decimal] = None  # 最大切片大小
    urgency: float = 0.5  # 紧急程度 (0-1)
    risk_aversion: float = 0.5  # 风险厌恶程度 (0-1)
    start_time: Optional[datetime] = None  # 开始时间
    end_time: Optional[datetime] = None  # 结束时间
    custom_params: Dict[str, Any] = field(default_factory=dict)  # 自定义参数


@dataclass
class ExecutionSlice:
    """执行切片"""
    slice_id: str  # 切片ID
    parent_order_id: str  # 父订单ID
    symbol: str  # 标的代码
    side: OrderSide  # 交易方向
    quantity: Decimal  # 切片数量
    target_time: datetime  # 目标执行时间
    price_limit: Optional[Decimal] = None  # 价格限制
    order_type: OrderType = OrderType.MARKET  # 订单类型
    status: ExecutionStatus = ExecutionStatus.PENDING  # 执行状态
    created_at: datetime = field(default_factory=datetime.now)
    executed_at: Optional[datetime] = None
    filled_quantity: Decimal = Decimal('0')
    avg_price: Optional[Decimal] = None
    metadata: Dict[str, Any] = field(default_factory=dict)


@dataclass
class ExecutionResult:
    """执行结果"""
    execution_id: str  # 执行ID
    parent_order_id: str  # 父订单ID
    algorithm: ExecutionAlgorithm  # 执行算法
    status: ExecutionStatus  # 执行状态
    total_quantity: Decimal  # 总数量
    executed_quantity: Decimal  # 已执行数量
    remaining_quantity: Decimal  # 剩余数量
    avg_price: Optional[Decimal] = None  # 平均价格
    total_cost: Decimal = Decimal('0')  # 总成本
    total_commission: Decimal = Decimal('0')  # 总手续费
    slices: List[ExecutionSlice] = field(default_factory=list)  # 执行切片
    start_time: Optional[datetime] = None  # 开始时间
    end_time: Optional[datetime] = None  # 结束时间
    duration: Optional[timedelta] = None  # 执行时长
    performance_metrics: Dict[str, float] = field(default_factory=dict)  # 性能指标
    error_message: Optional[str] = None  # 错误信息


class BaseExecutionStrategy(ABC):
    """基础执行策略抽象类"""
    
    def __init__(self, order_manager: OrderManager):
        """
        初始化执行策略
        
        Args:
            order_manager: 订单管理器
        """
        self.order_manager = order_manager
        self.is_running = False
        self.is_paused = False
    
    @abstractmethod
    async def execute(
        self,
        order: Order,
        params: ExecutionParams,
        market_data_callback: Optional[Callable] = None
    ) -> AsyncGenerator[ExecutionResult, None]:
        """
        执行订单
        
        Args:
            order: 待执行订单
            params: 执行参数
            market_data_callback: 市场数据回调函数
            
        Yields:
            ExecutionResult: 执行结果
        """
        # 这是一个抽象方法，子类必须实现
        if False:  # 这样可以让类型检查器知道这是一个异步生成器
            yield ExecutionResult(
                execution_id="",
                parent_order_id="",
                algorithm=ExecutionAlgorithm.MARKET,
                status=ExecutionStatus.PENDING,
                total_quantity=Decimal('0'),
                executed_quantity=Decimal('0'),
                remaining_quantity=Decimal('0')
            )
    
    @abstractmethod
    async def pause(self) -> bool:
        """暂停执行"""
        pass
    
    @abstractmethod
    async def resume(self) -> bool:
        """恢复执行"""
        pass
    
    @abstractmethod
    async def cancel(self) -> bool:
        """取消执行"""
        pass


class MarketExecutionStrategy(BaseExecutionStrategy):
    """市价执行策略"""
    
    async def execute(
        self,
        order: Order,
        params: ExecutionParams,
        market_data_callback: Optional[Callable] = None
    ) -> AsyncGenerator[ExecutionResult, None]:
        """市价执行"""
        execution_id = f"market_{order.order_id}"
        
        result = ExecutionResult(
            execution_id=execution_id,
            parent_order_id=order.order_id,
            algorithm=ExecutionAlgorithm.MARKET,
            status=ExecutionStatus.RUNNING,
            total_quantity=params.total_quantity,
            executed_quantity=Decimal('0'),
            remaining_quantity=params.total_quantity,
            start_time=datetime.now()
        )
        
        try:
            self.is_running = True
            
            # 创建市价单切片
            slice_order = ExecutionSlice(
                slice_id=f"slice_{execution_id}_1",
                parent_order_id=order.order_id,
                symbol=order.symbol,
                side=order.side,
                quantity=params.total_quantity,
                target_time=datetime.now(),
                order_type=OrderType.MARKET,
                status=ExecutionStatus.RUNNING
            )
            
            result.slices.append(slice_order)
            
            # 提交市价单
            market_order = await self.order_manager.create_order(
                symbol=order.symbol,
                side=order.side,
                order_type=OrderType.MARKET,
                quantity=params.total_quantity,
                strategy_id=order.strategy_id,
                execution_params={"execution_id": execution_id}
            )
            
            await self.order_manager.submit_order(market_order.order_id)
            
            # 等待订单完成
            while market_order and market_order.is_active and self.is_running:
                await asyncio.sleep(0.1)
                market_order = self.order_manager.get_order(market_order.order_id)
                
                if market_order:
                    result.executed_quantity = market_order.filled_quantity
                    result.remaining_quantity = market_order.remaining_quantity or Decimal('0')
                    result.avg_price = market_order.avg_fill_price
                    result.total_commission = market_order.total_commission
                    
                    if market_order.avg_fill_price:
                        result.total_cost = result.executed_quantity * market_order.avg_fill_price
                    
                    yield result
            
            # 更新最终状态
            if market_order and market_order.is_filled:
                result.status = ExecutionStatus.COMPLETED
                slice_order.status = ExecutionStatus.COMPLETED
                slice_order.executed_at = datetime.now()
                slice_order.filled_quantity = market_order.filled_quantity
                slice_order.avg_price = market_order.avg_fill_price
            else:
                result.status = ExecutionStatus.ERROR
                result.error_message = "Market order execution failed"
            
            result.end_time = datetime.now()
            if result.start_time:
                result.duration = result.end_time - result.start_time
            
            yield result
            
        except Exception as e:
            result.status = ExecutionStatus.ERROR
            result.error_message = str(e)
            result.end_time = datetime.now()
            yield result
        finally:
            self.is_running = False
    
    async def pause(self) -> bool:
        """市价单无法暂停"""
        return False
    
    async def resume(self) -> bool:
        """市价单无法恢复"""
        return False
    
    async def cancel(self) -> bool:
        """取消执行"""
        self.is_running = False
        return True


class TWAPExecutionStrategy(BaseExecutionStrategy):
    """TWAP执行策略"""
    
    async def execute(
        self,
        order: Order,
        params: ExecutionParams,
        market_data_callback: Optional[Callable] = None
    ) -> AsyncGenerator[ExecutionResult, None]:
        """TWAP执行"""
        execution_id = f"twap_{order.order_id}"
        
        result = ExecutionResult(
            execution_id=execution_id,
            parent_order_id=order.order_id,
            algorithm=ExecutionAlgorithm.TWAP,
            status=ExecutionStatus.RUNNING,
            total_quantity=params.total_quantity,
            executed_quantity=Decimal('0'),
            remaining_quantity=params.total_quantity,
            start_time=datetime.now()
        )
        
        try:
            self.is_running = True
            
            # 计算切片参数
            total_seconds = params.time_horizon.total_seconds()
            slice_interval = max(60, total_seconds / 20)  # 最少1分钟间隔
            num_slices = int(total_seconds / slice_interval)
            slice_quantity = params.total_quantity / num_slices
            
            # 生成执行切片
            current_time = params.start_time or datetime.now()
            for i in range(num_slices):
                target_time = current_time + timedelta(seconds=i * slice_interval)
                
                slice_order = ExecutionSlice(
                    slice_id=f"slice_{execution_id}_{i+1}",
                    parent_order_id=order.order_id,
                    symbol=order.symbol,
                    side=order.side,
                    quantity=slice_quantity,
                    target_time=target_time,
                    price_limit=params.price_limit,
                    order_type=OrderType.LIMIT if params.price_limit else OrderType.MARKET
                )
                
                result.slices.append(slice_order)
            
            # 执行切片
            for slice_order in result.slices:
                if not self.is_running:
                    break
                
                # 等待到目标时间
                while datetime.now() < slice_order.target_time and self.is_running:
                    if self.is_paused:
                        await asyncio.sleep(1)
                        continue
                    await asyncio.sleep(1)
                
                if not self.is_running:
                    break
                
                # 创建并提交订单
                slice_order.status = ExecutionStatus.RUNNING
                
                child_order = await self.order_manager.create_order(
                    symbol=slice_order.symbol,
                    side=slice_order.side,
                    order_type=slice_order.order_type,
                    quantity=slice_order.quantity,
                    price=slice_order.price_limit,
                    strategy_id=order.strategy_id,
                    execution_params={"execution_id": execution_id, "slice_id": slice_order.slice_id}
                )
                
                await self.order_manager.submit_order(child_order.order_id)
                
                # 等待切片完成或超时
                timeout = timedelta(minutes=5)
                start_wait = datetime.now()
                
                while child_order and child_order.is_active and self.is_running:
                    if datetime.now() - start_wait > timeout:
                        await self.order_manager.cancel_order(child_order.order_id, "TWAP timeout")
                        break
                    
                    await asyncio.sleep(1)
                    child_order = self.order_manager.get_order(child_order.order_id)
                    
                    if child_order:
                        slice_order.filled_quantity = child_order.filled_quantity
                        slice_order.avg_price = child_order.avg_fill_price
                        
                        # 更新总体结果
                        result.executed_quantity += child_order.filled_quantity
                        result.remaining_quantity = params.total_quantity - result.executed_quantity
                        
                        if child_order.avg_fill_price:
                            # 重新计算平均价格
                            if result.avg_price is None:
                                result.avg_price = child_order.avg_fill_price
                            else:
                                total_value = (result.executed_quantity - child_order.filled_quantity) * result.avg_price
                                total_value += child_order.filled_quantity * child_order.avg_fill_price
                                result.avg_price = total_value / result.executed_quantity
                        
                        result.total_commission += child_order.total_commission
                
                # 更新切片状态
                if child_order and child_order.is_filled:
                    slice_order.status = ExecutionStatus.COMPLETED
                elif child_order and child_order.is_cancelled:
                    slice_order.status = ExecutionStatus.CANCELLED
                else:
                    slice_order.status = ExecutionStatus.ERROR
                
                slice_order.executed_at = datetime.now()
                
                # 返回中间结果
                yield result
            
            # 更新最终状态
            if result.remaining_quantity <= 0:
                result.status = ExecutionStatus.COMPLETED
            elif not self.is_running:
                result.status = ExecutionStatus.CANCELLED
            else:
                result.status = ExecutionStatus.COMPLETED  # 部分完成
            
            result.end_time = datetime.now()
            if result.start_time:
                result.duration = result.end_time - result.start_time
            
            # 计算性能指标
            if result.avg_price and result.executed_quantity > 0:
                result.total_cost = result.executed_quantity * result.avg_price
                result.performance_metrics = {
                    "execution_rate": float(result.executed_quantity / params.total_quantity),
                    "avg_slice_size": float(result.executed_quantity / len([s for s in result.slices if s.status == ExecutionStatus.COMPLETED])) if result.slices else 0,
                    "time_efficiency": float(result.duration.total_seconds() / params.time_horizon.total_seconds()) if result.duration else 0
                }
            
            yield result
            
        except Exception as e:
            result.status = ExecutionStatus.ERROR
            result.error_message = str(e)
            result.end_time = datetime.now()
            yield result
        finally:
            self.is_running = False
    
    async def pause(self) -> bool:
        """暂停执行"""
        self.is_paused = True
        return True
    
    async def resume(self) -> bool:
        """恢复执行"""
        self.is_paused = False
        return True
    
    async def cancel(self) -> bool:
        """取消执行"""
        self.is_running = False
        return True


class VWAPExecutionStrategy(BaseExecutionStrategy):
    """VWAP执行策略"""
    
    async def execute(
        self,
        order: Order,
        params: ExecutionParams,
        market_data_callback: Optional[Callable] = None
    ) -> AsyncGenerator[ExecutionResult, None]:
        """VWAP执行"""
        execution_id = f"vwap_{order.order_id}"
        
        result = ExecutionResult(
            execution_id=execution_id,
            parent_order_id=order.order_id,
            algorithm=ExecutionAlgorithm.VWAP,
            status=ExecutionStatus.RUNNING,
            total_quantity=params.total_quantity,
            executed_quantity=Decimal('0'),
            remaining_quantity=params.total_quantity,
            start_time=datetime.now()
        )
        
        try:
            self.is_running = True
            
            # 获取历史成交量数据用于VWAP计算
            # 这里简化处理，实际应该从市场数据获取
            volume_profile = self._generate_volume_profile(params.time_horizon)
            
            # 根据成交量分布生成切片
            total_seconds = params.time_horizon.total_seconds()
            slice_interval = max(60, total_seconds / len(volume_profile))
            
            for i, volume_weight in enumerate(volume_profile):
                target_time = (params.start_time or datetime.now()) + timedelta(seconds=i * slice_interval)
                slice_quantity = params.total_quantity * Decimal(str(volume_weight))
                
                if slice_quantity > 0:
                    slice_order = ExecutionSlice(
                        slice_id=f"slice_{execution_id}_{i+1}",
                        parent_order_id=order.order_id,
                        symbol=order.symbol,
                        side=order.side,
                        quantity=slice_quantity,
                        target_time=target_time,
                        price_limit=params.price_limit,
                        order_type=OrderType.LIMIT if params.price_limit else OrderType.MARKET
                    )
                    
                    result.slices.append(slice_order)
            
            # 执行切片（类似TWAP逻辑）
            for slice_order in result.slices:
                if not self.is_running:
                    break
                
                # 等待到目标时间
                while datetime.now() < slice_order.target_time and self.is_running:
                    if self.is_paused:
                        await asyncio.sleep(1)
                        continue
                    await asyncio.sleep(1)
                
                if not self.is_running:
                    break
                
                # 执行切片订单
                await self._execute_slice(slice_order, order, execution_id, result)
                yield result
            
            # 更新最终状态
            result.status = ExecutionStatus.COMPLETED if result.remaining_quantity <= 0 else ExecutionStatus.CANCELLED
            result.end_time = datetime.now()
            if result.start_time:
                result.duration = result.end_time - result.start_time
            
            yield result
            
        except Exception as e:
            result.status = ExecutionStatus.ERROR
            result.error_message = str(e)
            result.end_time = datetime.now()
            yield result
        finally:
            self.is_running = False
    
    def _generate_volume_profile(self, time_horizon: timedelta) -> List[float]:
        """生成成交量分布曲线"""
        # 简化的U型成交量分布
        hours = int(time_horizon.total_seconds() / 3600)
        if hours <= 0:
            return [1.0]
        
        profile = []
        for i in range(hours):
            # U型分布：开盘和收盘时成交量大，中午成交量小
            if i < 2 or i >= hours - 2:  # 开盘和收盘前2小时
                weight = 0.3
            elif 2 <= i < 4 or hours - 4 <= i < hours - 2:  # 次高峰
                weight = 0.2
            else:  # 中间时段
                weight = 0.1
            profile.append(weight)
        
        # 归一化
        total_weight = sum(profile)
        return [w / total_weight for w in profile]
    
    async def _execute_slice(
        self,
        slice_order: ExecutionSlice,
        parent_order: Order,
        execution_id: str,
        result: ExecutionResult
    ) -> None:
        """执行单个切片"""
        slice_order.status = ExecutionStatus.RUNNING
        
        child_order = await self.order_manager.create_order(
            symbol=slice_order.symbol,
            side=slice_order.side,
            order_type=slice_order.order_type,
            quantity=slice_order.quantity,
            price=slice_order.price_limit,
            strategy_id=parent_order.strategy_id,
            execution_params={"execution_id": execution_id, "slice_id": slice_order.slice_id}
        )
        
        await self.order_manager.submit_order(child_order.order_id)
        
        # 等待切片完成
        timeout = timedelta(minutes=5)
        start_wait = datetime.now()
        
        while child_order and child_order.is_active and self.is_running:
            if datetime.now() - start_wait > timeout:
                await self.order_manager.cancel_order(child_order.order_id, "VWAP timeout")
                break
            
            await asyncio.sleep(1)
            child_order = self.order_manager.get_order(child_order.order_id)
            
            if child_order:
                slice_order.filled_quantity = child_order.filled_quantity
                slice_order.avg_price = child_order.avg_fill_price
                
                # 更新总体结果
                result.executed_quantity += child_order.filled_quantity
                result.remaining_quantity = result.total_quantity - result.executed_quantity
                result.total_commission += child_order.total_commission
        
        # 更新切片状态
        slice_order.status = ExecutionStatus.COMPLETED if child_order and child_order.is_filled else ExecutionStatus.ERROR
        slice_order.executed_at = datetime.now()
    
    async def pause(self) -> bool:
        """暂停执行"""
        self.is_paused = True
        return True
    
    async def resume(self) -> bool:
        """恢复执行"""
        self.is_paused = False
        return True
    
    async def cancel(self) -> bool:
        """取消执行"""
        self.is_running = False
        return True


class IcebergExecutionStrategy(BaseExecutionStrategy):
    """冰山执行策略"""
    
    async def execute(
        self,
        order: Order,
        params: ExecutionParams,
        market_data_callback: Optional[Callable] = None
    ) -> AsyncGenerator[ExecutionResult, None]:
        """冰山执行"""
        execution_id = f"iceberg_{order.order_id}"
        
        result = ExecutionResult(
            execution_id=execution_id,
            parent_order_id=order.order_id,
            algorithm=ExecutionAlgorithm.ICEBERG,
            status=ExecutionStatus.RUNNING,
            total_quantity=params.total_quantity,
            executed_quantity=Decimal('0'),
            remaining_quantity=params.total_quantity,
            start_time=datetime.now()
        )
        
        try:
            self.is_running = True
            
            # 计算显示数量
            display_quantity = params.slice_size or (params.total_quantity * Decimal('0.1'))  # 默认显示10%
            remaining = params.total_quantity
            slice_count = 0
            
            while remaining > 0 and self.is_running:
                if self.is_paused:
                    await asyncio.sleep(1)
                    continue
                
                # 计算当前切片大小
                current_slice = min(display_quantity, remaining)
                slice_count += 1
                
                slice_order = ExecutionSlice(
                    slice_id=f"slice_{execution_id}_{slice_count}",
                    parent_order_id=order.order_id,
                    symbol=order.symbol,
                    side=order.side,
                    quantity=current_slice,
                    target_time=datetime.now(),
                    price_limit=params.price_limit,
                    order_type=OrderType.LIMIT if params.price_limit else OrderType.MARKET,
                    status=ExecutionStatus.RUNNING
                )
                
                result.slices.append(slice_order)
                
                # 创建并提交订单
                child_order = await self.order_manager.create_order(
                    symbol=slice_order.symbol,
                    side=slice_order.side,
                    order_type=slice_order.order_type,
                    quantity=slice_order.quantity,
                    price=slice_order.price_limit,
                    strategy_id=order.strategy_id,
                    execution_params={"execution_id": execution_id, "slice_id": slice_order.slice_id}
                )
                
                await self.order_manager.submit_order(child_order.order_id)
                
                # 等待当前切片完成
                while child_order and child_order.is_active and self.is_running:
                    await asyncio.sleep(1)
                    child_order = self.order_manager.get_order(child_order.order_id)
                    
                    if child_order:
                        slice_order.filled_quantity = child_order.filled_quantity
                        slice_order.avg_price = child_order.avg_fill_price
                
                # 更新结果
                if child_order:
                    filled = child_order.filled_quantity
                    result.executed_quantity += filled
                    remaining -= filled
                    result.remaining_quantity = remaining
                    result.total_commission += child_order.total_commission
                    
                    if child_order.avg_fill_price:
                        if result.avg_price is None:
                            result.avg_price = child_order.avg_fill_price
                        else:
                            total_value = (result.executed_quantity - filled) * result.avg_price
                            total_value += filled * child_order.avg_fill_price
                            result.avg_price = total_value / result.executed_quantity
                
                slice_order.status = ExecutionStatus.COMPLETED if child_order and child_order.is_filled else ExecutionStatus.ERROR
                slice_order.executed_at = datetime.now()
                
                yield result
                
                # 如果切片未完全成交，等待一段时间再继续
                if child_order and not child_order.is_filled:
                    await asyncio.sleep(30)  # 等待30秒
            
            # 更新最终状态
            result.status = ExecutionStatus.COMPLETED if remaining <= 0 else ExecutionStatus.CANCELLED
            result.end_time = datetime.now()
            if result.start_time:
                result.duration = result.end_time - result.start_time
            
            yield result
            
        except Exception as e:
            result.status = ExecutionStatus.ERROR
            result.error_message = str(e)
            result.end_time = datetime.now()
            yield result
        finally:
            self.is_running = False
    
    async def pause(self) -> bool:
        """暂停执行"""
        self.is_paused = True
        return True
    
    async def resume(self) -> bool:
        """恢复执行"""
        self.is_paused = False
        return True
    
    async def cancel(self) -> bool:
        """取消执行"""
        self.is_running = False
        return True


class ExecutionEngine:
    """
    执行引擎
    
    管理和协调各种执行策略，提供统一的执行接口。
    """
    
    def __init__(self, order_manager: OrderManager):
        """
        初始化执行引擎
        
        Args:
            order_manager: 订单管理器
        """
        self.order_manager = order_manager
        self._strategies: Dict[ExecutionAlgorithm, BaseExecutionStrategy] = {}
        self._active_executions: Dict[str, BaseExecutionStrategy] = {}
        self._execution_results: Dict[str, ExecutionResult] = {}
        self._callbacks: Dict[str, List[Callable]] = {
            "execution_started": [],
            "execution_updated": [],
            "execution_completed": [],
            "execution_error": []
        }
        
        # 注册默认策略
        self._register_default_strategies()
    
    def _register_default_strategies(self) -> None:
        """注册默认执行策略"""
        self._strategies[ExecutionAlgorithm.MARKET] = MarketExecutionStrategy(self.order_manager)
        self._strategies[ExecutionAlgorithm.TWAP] = TWAPExecutionStrategy(self.order_manager)
        self._strategies[ExecutionAlgorithm.VWAP] = VWAPExecutionStrategy(self.order_manager)
        self._strategies[ExecutionAlgorithm.ICEBERG] = IcebergExecutionStrategy(self.order_manager)
    
    def register_strategy(self, algorithm: ExecutionAlgorithm, strategy: BaseExecutionStrategy) -> None:
        """注册执行策略"""
        self._strategies[algorithm] = strategy
    
    async def execute_order(
        self,
        order: Order,
        params: ExecutionParams,
        market_data_callback: Optional[Callable] = None
    ) -> str:
        """
        执行订单
        
        Args:
            order: 待执行订单
            params: 执行参数
            market_data_callback: 市场数据回调函数
            
        Returns:
            执行ID
        """
        if params.algorithm not in self._strategies:
            raise ValueError(f"Unsupported execution algorithm: {params.algorithm}")
        
        strategy = self._strategies[params.algorithm]
        execution_id = f"{params.algorithm.value}_{order.order_id}"
        
        # 启动执行任务
        strategy = self._strategies[params.algorithm]
        self._active_executions[execution_id] = strategy
        
        # 触发开始回调
        await self._trigger_callback("execution_started", execution_id, order, params)
        
        # 异步执行
        asyncio.create_task(self._run_execution(execution_id, order, params, strategy, market_data_callback))
        
        return execution_id
    
    async def _run_execution(
        self,
        execution_id: str,
        order: Order,
        params: ExecutionParams,
        strategy: BaseExecutionStrategy,
        market_data_callback: Optional[Callable] = None
    ) -> None:
        """运行执行任务"""
        try:
            async for result in strategy.execute(order, params, market_data_callback):
                self._execution_results[execution_id] = result
                await self._trigger_callback("execution_updated", execution_id, result)
                
                if result.status in [ExecutionStatus.COMPLETED, ExecutionStatus.CANCELLED, ExecutionStatus.ERROR]:
                    await self._trigger_callback("execution_completed", execution_id, result)
                    break
        except Exception as e:
            result = ExecutionResult(
                execution_id=execution_id,
                parent_order_id=order.order_id,
                algorithm=params.algorithm,
                status=ExecutionStatus.ERROR,
                total_quantity=params.total_quantity,
                executed_quantity=Decimal('0'),
                remaining_quantity=params.total_quantity,
                error_message=str(e)
            )
            self._execution_results[execution_id] = result
            await self._trigger_callback("execution_error", execution_id, result)
        finally:
            if execution_id in self._active_executions:
                del self._active_executions[execution_id]
    
    async def pause_execution(self, execution_id: str) -> bool:
        """暂停执行"""
        if execution_id in self._active_executions:
            return await self._active_executions[execution_id].pause()
        return False
    
    async def resume_execution(self, execution_id: str) -> bool:
        """恢复执行"""
        if execution_id in self._active_executions:
            return await self._active_executions[execution_id].resume()
        return False
    
    async def cancel_execution(self, execution_id: str) -> bool:
        """取消执行"""
        if execution_id in self._active_executions:
            return await self._active_executions[execution_id].cancel()
        return False
    
    def get_execution_result(self, execution_id: str) -> Optional[ExecutionResult]:
        """获取执行结果"""
        return self._execution_results.get(execution_id)
    
    def get_active_executions(self) -> List[str]:
        """获取活跃执行列表"""
        return list(self._active_executions.keys())
    
    def add_callback(self, event_type: str, callback: Callable) -> None:
        """添加回调函数"""
        if event_type in self._callbacks:
            self._callbacks[event_type].append(callback)
    
    def remove_callback(self, event_type: str, callback: Callable) -> None:
        """移除回调函数"""
        if event_type in self._callbacks and callback in self._callbacks[event_type]:
            self._callbacks[event_type].remove(callback)
    
    async def _trigger_callback(self, event_type: str, *args) -> None:
        """触发回调函数"""
        if event_type in self._callbacks:
            for callback in self._callbacks[event_type]:
                try:
                    if asyncio.iscoroutinefunction(callback):
                        await callback(*args)
                    else:
                        callback(*args)
                except Exception as e:
                    print(f"Callback error: {e}")
    
    async def get_execution_statistics(self) -> Dict[str, Any]:
        """获取执行统计信息"""
        stats = {
            "total_executions": len(self._execution_results),
            "active_executions": len(self._active_executions),
            "completed_executions": 0,
            "cancelled_executions": 0,
            "error_executions": 0,
            "algorithm_distribution": {},
            "avg_execution_time": 0,
            "total_executed_quantity": Decimal('0'),
            "total_cost": Decimal('0')
        }
        
        total_duration = timedelta()
        completed_count = 0
        
        for result in self._execution_results.values():
            # 状态统计
            if result.status == ExecutionStatus.COMPLETED:
                stats["completed_executions"] += 1
            elif result.status == ExecutionStatus.CANCELLED:
                stats["cancelled_executions"] += 1
            elif result.status == ExecutionStatus.ERROR:
                stats["error_executions"] += 1
            
            # 算法分布
            algo_name = result.algorithm.value
            stats["algorithm_distribution"][algo_name] = stats["algorithm_distribution"].get(algo_name, 0) + 1
            
            # 执行时间统计
            if result.duration:
                total_duration += result.duration
                completed_count += 1
            
            # 数量和成本统计
            stats["total_executed_quantity"] += result.executed_quantity
            stats["total_cost"] += result.total_cost
        
        # 平均执行时间
        if completed_count > 0:
            stats["avg_execution_time"] = total_duration.total_seconds() / completed_count
        
        return stats